package com.hc.programming.array;

import java.util.ArrayList;
import java.util.List;

/**
 * 54.给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * <p>
 * 示例 1：
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * 示例 2：
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 * <p>
 * 提示：
 * m == matrix.length
 * n == matrix[i].length
 * 1 <= m, n <= 10
 * -100 <= matrix[i][j] <= 100
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/7/8 10:59
 */
public class 螺旋矩阵 {
    public static void main(String[] args) {
        System.out.println(spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
        System.out.println(spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}));
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return new ArrayList<>();
        }
        List<Integer> result = new ArrayList<>(matrix.length * matrix[0].length);
        // 墙：横向
        int wall_row_min = 0;
        int wall_row_max = matrix.length - 1;
        // 墙：纵向
        int wall_col_min = 0;
        int wall_col_max = matrix[0].length - 1;
        int idx_row = 0; // 横向指针
        int idx_col = 0; // 纵向指针
        while (wall_col_min <= wall_col_max) {
            // 向右移动
            for (int i = wall_col_min; i <= wall_col_max; i++) {
                result.add(matrix[idx_row][i]);
            }
            wall_row_min++; // 上边墙下移
            if (wall_row_min > wall_row_max) break;
            idx_col = wall_col_max;
            // 向下移动
            for (int i = wall_row_min; i <= wall_row_max; i++) {
                result.add(matrix[i][idx_col]);
            }
            wall_col_max--; // 右边墙左移
            if (wall_col_min > wall_col_max) break;
            idx_row = wall_row_max;
            // 向左移动
            for (int i = wall_col_max; i >= wall_col_min; i--) {
                result.add(matrix[idx_row][i]);
            }
            wall_row_max--; // 下边墙上移
            if (wall_row_min > wall_row_max) break;
            idx_col = wall_col_min;
            // 向上移动
            for (int i = wall_row_max; i >= wall_row_min; i--) {
                result.add(matrix[i][idx_col]);
            }
            wall_col_min++; // 左边墙右移
            idx_row = wall_row_min;
        }
        return result;
    }
}
